<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/13
 * Time: 10:18
 */

namespace App\Rep;


use App\Models\Customer;
use Illuminate\Support\Facades\DB;

class CustomerRep
{
    /**
     * 获取客户列表
     * @param $params
     * @return mixed
     */
    public function getCustomerListRep($params){
        $list = Customer::Search($params)->paginate($params['per_page']??1000);
        return $list;
    }

    /**
     * 添加客户
     * @param $params
     * @return Customer|array
     */
    public function createCustomerRep($params){
        if(isset($params['id']) && !empty($params['id'])){
            $model = Customer::where('id',$params['id'])->first();
        }else{
            $model = new Customer();
        }
        $model->customer_name = $params['customer_name'];
        $model->provinces = $params['provinces'];
        $model->city = $params['city'];
        $model->county = $params['county'];
        $model->customer_address = $params['customer_address'];
        $model->contact = $params['contact'];
        $model->contact_phone = $params['contact_phone'];
        $model->remark = $params['remark']??'';
        if(isset($params['balance'])){
            $model->balance = $params['balance'];
        }
        $model->save();
        return ['code'=>0,'data'=>$model,'msg'=>'success'];
    }

    /**
     * 删除客户
     * @param $params
     */
    public function delCustomerRep($params){
        $model = Customer::where('id',$params['id'])->first();
        $model->is_del = $params['is_del'];
        $model->save();
        return $model;
    }

    /**
     * 充值
     * @param $params
     */
    public function topUpRep($params){
        DB::beginTransaction();
        try{
            $model = Customer::where('id',$params['id'])->first();
            //添加资金变动记录
            $balanceHistoryRep = new BalanceHistoryRep();
            $balanceHistoryRep->addBalanceHistoryRep($params['id'],$params['balance'],$model->balance,$model->balance + $params['balance'],0,'余额充值',$detail='');

            $model->balance = $model->balance + $params['balance'];
            $model->save();
            DB::commit();
            return ['code'=>0,'data'=>$model,'msg'=>'success'];
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }

    }
}
